<?php
defined('BY_JYA') or exit('error');
/*
	加盟
*/
$_RQ['op']=$_RQ['op']?$_RQ['op']:'join';

if($_RQ['op']=='join'){
	//申请代理商
	if($_RQ['postdata']){
		$post=get_postdata();
		
		if($post['pcd']){
			if($post['pcd']['province']){
				//省级代理
				$code=pdo_getcolumn('core_area',array('type'=>1,'title'=>$post['pcd']['province']),'code');
				$type=1;
			}
			if($post['pcd']['city']){
				$code=pdo_getcolumn('core_area',array('type'=>2,'parent_code'=>$code,'title'=>$post['pcd']['city']),'code');
				$type=2;
			}
			if($post['pcd']['district']){
				$code=pdo_getcolumn('core_area',array('type'=>3,'parent_code'=>$code,'title'=>$post['pcd']['district']),'code');
				$type=3;
			}
			$check=$this->getcolumn('agent',array('uniacid'=>$_SESSION['uniacid'],'area_code'=>$code),'id');
			if($check){
				exi('该地区已存在代理商，请选择其他地区！','error');
			}
			$data['type']=$type;
			$data['area_code']=$code;
		}
		$new_agent=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$_SESSION['uid'],
			'agent_id'=>intval($post['agent_id']),
			'createtime'=>TIMESTAMP,
			'type'=>$type,
			'area_code'=>$code,
		);
		
		$this->insert('agent',$new_agent);
		$member_update=array();
		if($post['realname']){
			$member_update['realname']=trim($post['realname']);
		}
		if($post['mobile']){
			$member_update['mobile']=trim($post['mobile']);
			$check=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'mobile'=>$member_update['mobile']),'id');
			if($check && $check!=$_SESSION['uid']){
				exi('手机号码已存在，请更换~','error');
			}
		}
		if($member_update){
			pdo_update('core_members',$member_update,array('id'=>$_SESSION['uid']));
		}
		exi('申请成功！请等待管理员审核！','','/member.index/');
	}
	$mid=intval($_RQ['mid']);
	
	if($mid==$_SESSION['uid']){
		exi('不能自己添加自己为代理哦！','error','/member.index/');
	}
	$htmls=array(
		'title'=>'申请成为代理',
		'list'=>array(
			array('type'=>'string','name'=>'realname','title'=>'姓名','options'=>'areas'),
			array('type'=>'string','name'=>'mobile','title'=>'电话'),
			array('type'=>'pcd','name'=>'pcd','title'=>'代理地区','options'=>'areas','street'=>false),
			array('type'=>'submit','post'=>true,'url'=>'join','data'=>'item','title'=>'提交申请','icon'=>'fa-plus-square-o'),
		),
	);
	if($mid){
		$return['areas']=$this->get_agent_areas($mid);
	}else{
		$return['areas']=cfc('tools')->pcd();
	}
	
	$item=pdo_get('core_members',array('id'=>$_SESSION['uid']),array('realname','mobile'));
	$item['agent_id']=$mid;
	$return['item']=$item;
	$return['htmls']=$htmls;
	exi($return);
}